package me.lc.hammerheads.util;

import me.lc.hammerheads.core.GameManager;
import me.lc.hammerheads.core.GameSystem;
import me.lc.hammerheads.core.StageManager;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;

import com.admogo.AdMogoLayout;
import com.admogo.AdMogoListener;
import com.wiyun.engine.utils.ResolutionIndependent;

public class ADHelper implements AdMogoListener {
	private static final String mogoID = "903ca1f88f684c42817041419505dacf";
	private static ADHelper Instance = new ADHelper();
	private static AdMogoLayout adMogoLayoutCode;

	private static int maxBonusCount = 2;
	private static int bonusCount = 0;

	private static Object syncObj = new Object();
	private static boolean isShowed = false;

	private ADHelper() {
	}

	public static void initAD() {
		GameSystem.AndroidContext.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				synchronized (syncObj) {
					if (AppControl.isShowAd() && !isShowed) {
						isShowed = true;
						adMogoLayoutCode = new AdMogoLayout(
								GameSystem.AndroidContext, mogoID);
						FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
								FrameLayout.LayoutParams.FILL_PARENT,
								(int) ResolutionIndependent.resolveDp(50));
						// 设置广告出现的位置(悬浮于顶)
						params.gravity = Gravity.TOP;
						params.bottomMargin = 0;
						params.leftMargin = 0;
						// 添加广告状态监听
						adMogoLayoutCode.setAdMogoListener(ADHelper.Instance);
						GameSystem.AndroidContext.addContentView(
								adMogoLayoutCode, params);
						hideAd();
					}

				}

			}
		});
	}

	public static void showAd() {
		if (adMogoLayoutCode != null) {
			GameSystem.AndroidContext.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					adMogoLayoutCode.setVisibility(View.VISIBLE);
				}
			});
		}
	}

	public static void hideAd() {
		if (adMogoLayoutCode != null) {
			GameSystem.AndroidContext.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					adMogoLayoutCode.setVisibility(View.INVISIBLE);
				}
			});
		}
	}

	@Override
	public synchronized void onClickAd() {

		// 暂停时点广告有奖励
		if (GameManager.instance.isPaused) {
			// 增加2000金币
			if (bonusCount < maxBonusCount) {
				StageManager.instance.goldCount += 2000;
				StageManager.instance.saveGoldCount();
				GameManager.instance.updateGold();
				bonusCount++;
			}
		} else {
			// 点击广告暂停游戏
			GameManager.instance.pauseGame();
		}
	}

	@Override
	public void onCloseMogoDialog() {

	}

	@Override
	public void onFailedReceiveAd() {

	}

	@Override
	public void onReceiveAd() {

	}

	@Override
	public void onCloseAd() {
		// TODO Auto-generated method stub

	}

}
